import Vue from 'vue'

import Vuex from 'vuex'
import http from '@/utils/http.js'
Vue.use(Vuex)
let timeBox = -1;
const store = new Vuex.Store({
	state: {
		userInfo: uni.getStorageSync('user'),
		//消息
		message_id: 0, //当前消息id
		page: 1,
		total: 0,
		msgList: [],
		count_nored: 0,
		msgInfoList: [],
		lastMsgId: '',
		socketTask: null
	},
	mutations: {
		setMsgList(state, data) {
			state.msgList = data.list.data
			state.count_nored = data.count_nored
		},
		setMsgInfoList(state, data) {
			let vulue = [...data.data.reverse(), ...state.msgInfoList]
			state.msgInfoList = vulue
			if (state.page == 1) {
				this.commit('scrollToBottom');
			} else {
				this.commit('scrollToBottom', data.data.length);  
			}
			state.total = data.total
		},
		pushMsgInfoList(state, data) {
			let vulue = [...state.msgInfoList, data]
			state.msgInfoList = vulue
		},
		// 滚动到底部
		scrollToBottom(state, type = 0) {
			if (type == 0) {
				state.lastMsgId = 'msg' + (state.msgInfoList.length - 1);
			} else {
				state.lastMsgId = 'msg' + type;
			}
			// console.log(state.lastMsgId);
			
		},
		heartbeat(state) {
			clearInterval(timeBox);
			timeBox = setInterval(() => {
				// 发送到服务器
				state.socketTask.send({
					data: '{"type":"init",}',
				});
			}, 3000)
		},
		establish(state) {
			state.socketTask = uni.connectSocket({
				url: 'wss://work.cnyiji.cn/wss',
				success: () => console.log('Socket Connected')
			});
		},
	},
	actions: {
		// 连接 WebSocket
		connectWebSocket(content) {
			content.commit("establish")

			// 监听消息
			content.state.socketTask.onMessage(res => {
				const msg = JSON.parse(res.data);
				content.dispatch('receiveMessage', msg);
			});

			// 建立连接
			content.state.socketTask.onOpen(res => {
				console.warn("建立连接")
				content.commit("heartbeat")
			});

			// 监听 WebSocket 错误 
			content.state.socketTask.onError(res => {
				console.warn("socket错误")
				content.commit("establish")
			});

			// 监听 WebSocket 连接关闭
			content.state.socketTask.onClose(res => {
				console.error("连接关闭");
				clearInterval(timeBox);
				// socketBox.id = null;
				content.commit("establish")
			});
		},
		// 接收消息
		async receiveMessage(content, msg) {
			// console.log(msg);
			if (msg.client_id) {
				let res = await http("api/message/connect", {
					client_id: msg.client_id
				})
			}
			if (msg.data) {
				let pages = getCurrentPages();
				let routerUrl = pages[pages.length - 1].route //获取当前页的路径

				// 聊天页面
				if (routerUrl == "pages/index/privateMessage") {
					content.dispatch('messageOne');
					content.commit("scrollToBottom")
				} else { //消息列表
					content.dispatch('messageList');
				}
			}
		},
		// 新接收单条聊天记录
		async messageOne(content) {
			if (!content.state.message_id) return
			let res = await http("api/message/messageInfo", {
				message_id: content.state.message_id, //是	string		消息id
				page: "1", //是	string		当前页
				size: "1", //是	string		每页数据
			}, "GET")
			// console.log(res);
			if (res.code == 200) {
				content.commit("pushMsgInfoList", res.result.data[0])
				content.commit("scrollToBottom")
			}
		},
		// 发起消息
		async sendMessage(content, data) {
			let res = await http("api/message/send", {
				another_id: data.another_id, //是	int		对方uid
				content: data.content, //是	int		消息内容
				type: 1, //是	int		消息类型 1文字 2图片
			})

			if (res.code == 200) {
				const newMsg = {
					content: data.content,
					created_at: new Date().toLocaleTimeString([], {
						hour: '2-digit',
						minute: '2-digit'
					}),
					user: {
						avatar: content.state.userInfo.avatar
					},
					is_send: 1
				};
				content.commit("pushMsgInfoList", newMsg)
				content.commit("scrollToBottom")
				return true
			}
			return false
		},
		//单个聊天记录详情
		async messageInfo(content) {
			if (!content.state.message_id) return
			let res = await http("api/message/messageInfo", {
				message_id: content.state.message_id, //是	string		消息id
				page: content.state.page, //是	string		当前页
				size: "20", //是	string		每页数据
			}, "GET")
			// console.log(res);
			if (res.code == 200) {
				content.commit("setMsgInfoList", res.result)
				return res.result
				// content.commit("scrollToBottom")
			}
		},
		//获取会话聊天列表
		async messageList(content) {
			let res = await http("api/message/messageList", {}, "GET")
			if (res.code == 200) {
				content.commit("setMsgList", res.result)
			}
		}
	}
})
export default store